package com.kun.config;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.kun.entity.User;
import com.kun.service.UserService;
import com.kun.util.MD5ProducterUtil;
import com.kun.util.UserExcludePwdUtil;

import javax.annotation.Resource;

/**
 * @description: 微信登录realm
 * @author: KM
 * 2018年4月15日 下午11:13:50
 */
public class MySecondRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限配置-->MySecondRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //String username  = (String)principals.getPrimaryPrincipal();
        //查权限
//        for(SysRole role:userInfo.getRoleList()){
//            authorizationInfo.addRole(role.getRole());
//            for(SysPermission p:role.getPermissions()){
//                authorizationInfo.addStringPermission(p.getPermission());
//            }
//        }
        return authorizationInfo;
    }

    //身份校验
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        System.out.println("MySecondRealm.doGetAuthenticationInfo()");
        //获取用户的openId.
        String openId = (String)token.getPrincipal();
        User user = new User();
    	System.out.println(token.getCredentials());
        user = userService.selectUserByWechat(openId);
        System.out.println("----->>userInfo="+user);
        if(user == null){
        	throw new AccountException("未知错误");
        }
        String saltString = user.getUsername() + user.getSalt();
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
        		UserExcludePwdUtil.exclude(user), //user
        		MD5ProducterUtil.generate(user.getWechat(), saltString), //openId
        		ByteSource.Util.bytes(saltString),//salt=username+realSalt
                getName()  //realm name
        );
        return authenticationInfo;
    }

}